<template>
  <page-dialog
    :title="'执行巡检' + title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
      <dialog-table
        ref="resourceTable"
        v-model:data="tableInfo.data"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :check-box="false"
        :tab-index="true"
        :pager="false"
      >
        <template v-slot:col-preReferenceRangeStart="scope">
          <template v-if="scope.row.preItemType == 3">
            {{ scope.row.preReferenceRangeStart }} ~{{
              scope.row.preReferenceRangeEnd
            }}
          </template>
          <template v-else>
            <span>-</span>
          </template>
        </template>
        <template v-slot:col-preCustomOptionList="scope">
          <template v-if="scope.row.preItemType == 1">
            <el-checkbox-group
              v-model="scope.row.checkList"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              @change="changeResult(scope.row)"
            >
              <el-checkbox
                v-for="(item, index) in scope.row.preCustomOptionList"
                :key="index + Math.random()"
                :label="index"
                >{{ item.itemDetailName }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
          <template v-else-if="scope.row.preItemType == 2">
            <!--<el-radio v-for="(item, index) in scope.row.preCustomOptionList" :key="index + Math.random()" v-model="item.checkedNormal" :label="item.isChecked" :checked="item.isChecked" @change="changeResult(scope.row)">{{ item.itemDetailName }}</el-radio>-->
            <el-radio-group
              v-model="scope.row.radio"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              @change="changeResult(scope.row)"
            >
              <el-radio
                v-for="(item, index) in scope.row.preCustomOptionList"
                :key="index + Math.random()"
                :label="index"
                >{{ item.itemDetailName }}</el-radio
              >
            </el-radio-group>
          </template>
          <template v-else-if="scope.row.preItemType == 3">
            <el-form-item
              :prop="`data.${scope.$index}.preCustomOptionList[0].patrolResult`"
              :rules="scope.$index >= 0 ? [
                {
                  validator: $validate.allNumber,
                  trigger: 'blur',
                },
              ] : []"
            >
              <el-input
                v-model="scope.row.preCustomOptionList[0].patrolResult"
                :disabled="orderStatus !== 2 || orderSource !== 1"
                controls-position="right"
                placeholder="请输入巡检结果"
                style="width: 100%; margintop: 18px"
                @change="changeResult(scope.row)"
              ></el-input>
            </el-form-item>
          </template>
          <template v-else-if="scope.row.preItemType == 4">
            <el-input
              v-model="scope.row.preCustomOptionList[0].patrolResult"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              style="width: 100%"
              placeholder="请输入巡检结果"
              @change="changeResult(scope.row)"
            ></el-input>
          </template>
        </template>
        <template v-slot:col-patrolResultValue="scope">
          <template v-if="scope.row.preItemType == 4">
            <el-radio-group
              v-model="scope.row.patrolResult"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              @change="changeTextResult(scope.row)"
            >
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">异常</el-radio>
            </el-radio-group>
          </template>
          <template v-else-if="scope.row.preItemType == 1">
            <el-radio-group
              v-if="
                scope.row.preIsRequired === 0 &&
                scope.row.checkList &&
                scope.row.checkList.length === 0
              "
              v-model="scope.row.patrolResult"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              @change="changeTextResult(scope.row)"
            >
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">异常</el-radio>
            </el-radio-group>
            <span v-else>{{ scope.row.patrolResultValue }}</span>
          </template>
          <template v-else-if="scope.row.preItemType == 2">
            <el-radio-group
              v-if="scope.row.preIsRequired === 0 && scope.row.radio === ''"
              v-model="scope.row.patrolResult"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              @change="changeTextResult(scope.row)"
            >
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">异常</el-radio>
            </el-radio-group>
            <span v-else>{{ scope.row.patrolResultValue }}</span>
          </template>
          <template v-else-if="scope.row.preItemType == 3">
            <el-radio-group
              v-if="
                scope.row.preIsRequired === 0 &&
                !(
                  scope.row.preCustomOptionList[0].patrolResult ||
                  scope.row.preCustomOptionList[0].patrolResult === 0
                )
              "
              v-model="scope.row.patrolResult"
              :disabled="orderStatus !== 2 || orderSource !== 1"
              @change="changeTextResult(scope.row)"
            >
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="0">异常</el-radio>
            </el-radio-group>
            <span v-else>{{ scope.row.patrolResultValue }}</span>
          </template>
        </template>
      </dialog-table>
    </el-form>
  </page-dialog>
</template>
<script setup name="patrolAreaDetails">
import PageDialog from "@/components/PageDialog/index";
import DialogTable from "@/components/DialogTable/index";
import {
  getPlanTaskItemAll,
  planTaskItemUpdateBatchList,
} from "@/api/patrol.js";

const { proxy } = getCurrentInstance();
const emit = defineEmits();

const props = defineProps([
  "showDialog",
  "title",
  "id",
  "orderStatus",
  "orderSource",
]);

const filterInfo = reactive({
  query: {
    taskAreaId: props.id,
  },
});
// 表格相关
const tableInfo = reactive({
  data: [],
  fieldList: [
    { label: "巡检项目名称", value: "preItemName" },
    { label: "必填", value: "preIsRequiredValue" },
    { label: "参考范围", value: "preReferenceRangeStart", type: "slot" },
    {
      label: "巡检结果",
      value: "preCustomOptionList",
      type: "slot",
      minWidth: "240px",
    },
    { label: "正常/异常", value: "patrolResultValue", type: "slot" },
    { label: "备注", value: "remark", type: "input", maxlength: 200 },
  ],
});
// 弹窗相关
const dialogInfo = reactive({
  width: "90%",
  btLoading: false,
  btList: [
    { label: "关闭", event: handleClose, show: true },
    {
      label: "保存",
      type: "primary",
      event: save,
      show: true,
    },
  ],
});
const shows = computed({
  get() {
    return props.showDialog;
  },
  set(newValue) {
    emit("update:showDialog", newValue); // 更新父组件shows
  },
});

dialogInfo.btList[1].disabled =
  props.orderStatus !== 2 || props.orderSource !== 1;
getList();

function changeResult(row) {
  if (row.preItemType === 1) {
    let preCustomOptionList = row.preCustomOptionList;
    let checkList = row.checkList;
    let arr = [];
    if (checkList.length) {
      preCustomOptionList.forEach((item, index) => {
        item.isChecked = false;
        let checkItem = checkList.find((item) => item === index);
        if (checkItem || checkItem === 0) {
          item.isChecked = true;
          arr.push(item.checkedNormal);
        }
      });
    }
    if (arr.length) {
      let list = arr.filter((item) => item === 0);
      if (list.length) {
        row['patrolResultValue'] = "异常"
        row['patrolResult'] = 0
      } else {
        row['patrolResultValue'] = "正常"
        row['patrolResult'] = 1
      }
    } else {
      if (row.preIsRequired == 0) {
        row['patrolResultValue'] = "正常"
          row['patrolResult'] = 1
      } else {
        row['patrolResultValue'] = ""
        row['patrolResult'] = ''
      }
    }
  } else if (row.preItemType === 2) {
    let preCustomOptionList = row.preCustomOptionList;
    let radio = row.radio;
    let str = "";
    if (radio || radio === 0) {
      preCustomOptionList.forEach((item, index) => {
        item.isChecked = false;
        if (radio === index) {
          str = item.checkedNormal;
          item.isChecked = true;
        }
      });
    }
    if (str === 0) {
      row['patrolResultValue'] = "异常"
        row['patrolResult'] = 0
    } else if (str === 1) {
      row['patrolResultValue'] = "正常"
        row['patrolResult'] = 1
    }
  } else if (row.preItemType === 3) {
    let patrolResult = row.preCustomOptionList[0].patrolResult;
    console.log(patrolResult);
    if (patrolResult) {
      if (
        parseFloat(patrolResult) >= row.preReferenceRangeStart &&
        parseFloat(patrolResult) <= row.preReferenceRangeEnd
      ) {
        row['patrolResultValue'] = "正常"
        row['patrolResult'] = 1
      } else {
        row['patrolResultValue'] = "异常"
        row['patrolResult'] = 0
      }
    } else {
      if (row.preIsRequired === 0) {
        row['patrolResultValue'] = "正常"
        row['patrolResult'] = 1
      } else {
        row['patrolResultValue'] = ""
        row['patrolResult'] = ''
      }
    }
  }
}
function changeTextResult(row) {
  if (row.patrolResult === 0) {
    row.patrolResultValue = "异常";
  } else if (row.patrolResult === 1) {
    row.patrolResultValue = "正常";
  }
}
function getList() {
  getPlanTaskItemAll(filterInfo.query).then((res) => {
    if (res && res.success) {
      tableInfo.data = res.data;
      tableInfo.data.forEach((item) => {
        if (item.preItemType == 1) {
          let checkList = [];
          if (item.patrolResult === -2) {
            if (item.preIsRequired == 0) {
              item['patrolResultValue'] = '正常'
              item['patrolResult'] = 1
            }
          } else {
            item.preCustomOptionList.forEach((row, index) => {
              if (row.isChecked) {
                checkList.push(index);
              }
            });
          }
          item['checkList'] = checkList
        } else if (item.preItemType == 2) {
          let index = "";
          if (item.patrolResult === -2) {
            if (item.preIsRequired == 0) {
              item['patrolResultValue'] = '正常'
              item['patrolResult'] = 1
            }
          } else {
            index = item.preCustomOptionList.findIndex((row) => row.isChecked);
          }
          item['radio'] = index
        } else if (item.preItemType == 3) {
          if (item.patrolResult === -2) {
            //未检
            if (item.preDefaultValue) {
              //有默认值
              item.preCustomOptionList[0].patrolResult = parseFloat(
                item.preDefaultValue
              );
              if (
                item.preCustomOptionList[0].patrolResult >=
                  item.preReferenceRangeStart &&
                item.preCustomOptionList[0].patrolResult <=
                  item.preReferenceRangeEnd
              ) {
                item['patrolResultValue'] = '正常'
                item['patrolResult'] = 1
              } else {
                item['patrolResultValue'] = '异常'
                item['patrolResult'] = 0
              }
            } else {
              //没有默认值
              if (item.preIsRequired == 0) {
                item['patrolResultValue'] = '正常'
                item['patrolResult'] = 1
              }
            }
          }
          //item.preCustomOptionList[0].patrolResult = (item.preCustomOptionList[0].patrolResult || item.preCustomOptionList[0].patrolResult === 0) ? item.preCustomOptionList[0].patrolResult : undefined
        } else if (item.preItemType == 4) {
          if (item.patrolResult === -2) {
            //未检
            if (item.preDefaultValue) {
              //有默认值
              item.preCustomOptionList[0].patrolResult = item.preDefaultValue;
            }
            item['patrolResultValue'] = '正常'
                item['patrolResult'] = 1
          }
        }
        console.log(tableInfo.data);
      });
    }
  });
}
function save() {
  let arr = [];
  let tableData = proxy.$fn.deepClone(tableInfo.data);
  proxy.$refs["tableForm"].validate((valid) => {
    if (valid) {
      tableData.forEach((item) => {
        if (item.preIsRequired === 1) {
          if (item.preItemType === 1 || item.preItemType === 2) {
            let rowList = item.preCustomOptionList.filter(
              (row) => row.isChecked
            );
            if (!rowList.length) {
              arr.push(item);
            }
          } else if (item.preItemType === 3 || item.preItemType === 4) {
            if (
              item.patrolResult === -2 ||
              (!item.preCustomOptionList[0].patrolResult &&
                item.preCustomOptionList[0].patrolResult !== 0)
            ) {
              arr.push(item);
            }
          }
        } else {
          if (
            item.preItemType === 3 &&
            item.preCustomOptionList[0].patrolResult === undefined
          ) {
            item.preCustomOptionList[0].patrolResult = "";
          }
        }
      });
      if (arr.length) {
        proxy.$message({
          message: "请填写完必填项",
          type: "warning",
          duration: 3500,
          showClose: true,
        });
        return;
      }
      let patrolResultList = tableData
        .filter((item) => item.preIsRequired === 0)
        .filter((item) => !!(item.patrolResult !== 0));
      if (patrolResultList.length) {
        patrolResultList.forEach((item) => {
          item['patrolResultValue'] = '正常'
                item['patrolResult'] = 1
        });
      }
      console.log(tableData);
      planTaskItemUpdateBatchList(tableData).then((res) => {
        if (res && res.success) {
          handleClose();
          emit("callback");
        }
      });
    }
  });
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false;
  emit("reset");
}
</script>
